import { DirectiveBinding, ref, watch } from 'vue';

const isInViewport = ref(true);
let currentBinding: DirectiveBinding | null = null;

const handleIntersection = (entries: IntersectionObserverEntry[]) => {
  isInViewport.value = entries[0].isIntersecting;
  // 处理元素进入或离开视口的逻辑
};

const observerOptions: IntersectionObserverInit = {
  // 可选：设置其他配置选项，如阈值、根元素等
};

const observer = new IntersectionObserver(handleIntersection, observerOptions);

export default {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    observer.observe(el);
    currentBinding = binding;
    if (binding.value) {
      binding.value(isInViewport.value);
    }
  },
  unmounted(el: HTMLElement) {
    observer.unobserve(el);
  }
};

watch(isInViewport, (newValue) => {
  if (currentBinding && currentBinding.value) {
    currentBinding.value(newValue);
  }
});